#include "timechart_blck.h"
#include "ui_timechart_blck.h"
#include <QFileDialog>
#include <QDebug>
#include <QHeaderView>
#include <QDateTime>
#include <QShortcut>
#include <QTime>
timechart_blck::timechart_blck(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::timechart_blck)
{
    ui->setupUi(this);
    // --------------------------------------------
    // 初始化默认的参数
    //get settings
    QString setting_ini = QApplication::applicationDirPath() + "/setting.ini";
    settings = new QSettings(setting_ini,QSettings::IniFormat);
    QString timechart_dir_saved = settings->value("timechart_dir_saved",QApplication::applicationDirPath() +"/user_data/timechart_blck" ).toString();
    ui->ui_lin_dir->setText(timechart_dir_saved);
    // --------------------------------------------
    // 计算字符宽度
    // 获取表格当前字体的字体度量
    QFontMetrics fm(QApplication::font());
    // 方法1：使用平均字符宽度（适用于大多数场景）
    int charWidth = fm.averageCharWidth();
    int columnWidth = charWidth * 20;  // 20个字符的宽度
    // --------------------------------------------
    // 创建每天、星期、季度、项目目标规划表格
    int QUARTUS_MAX = 12; //最大12个季度
    int WEEK_MAX = QUARTUS_MAX * 12; //每个季度12周
    int DAY_MAX  = WEEK_MAX * 7; //每周7天

    table_day = new QTableWidget(24,DAY_MAX,this);
    ui->ui_pages->addTab(table_day,"time_day");

    //创建每天的时间表
    //table_day->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    table_day->horizontalHeader()->setDefaultSectionSize(columnWidth);
    table_day->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    // table_day->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    table_day->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    //table_day->resizeColumnsToContents();
    table_day->resizeRowsToContents();

    //创建每周的规划
    table_week = new QTableWidget(7,WEEK_MAX,this);
    ui->ui_pages->addTab(table_week,"time_week");
    //创建每周的时间表

    table_week->horizontalHeader()->setDefaultSectionSize(columnWidth);
    table_week->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    table_week->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    table_week->resizeRowsToContents();

    //创建每季度的规划
    table_quarter = new QTableWidget(12,QUARTUS_MAX,this);
    ui->ui_pages->addTab(table_quarter,"time_quarter");
    //创建每周的时间表

    table_quarter->horizontalHeader()->setDefaultSectionSize(columnWidth);
    table_quarter->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    table_quarter->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    table_quarter->resizeRowsToContents();

    //创建项目的规划
    table_team = new QTableWidget(12,1,this);
    ui->ui_pages->addTab(table_team,"time_team");
    //创建项目的时间表
    //table_team->horizontalHeader()->setDefaultSectionSize(columnWidth);
    table_team->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    table_team->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    table_team->resizeColumnsToContents();
    table_team->resizeRowsToContents();
    // --------------------------------------------
    // 初始化时间
    ui->ui_date_cur->setDate(QDate::currentDate()); //初始化为当前的时间
    ui->ui_date_cur->setEnabled(false); //当前时间不可编辑
    // 判断当前目录下是否存在时间管理的项目文件
    QFile f_ini(timechart_dir_saved + "/plan.ini"); //判断是否存在对应的配置文件
    if(f_ini.exists()) //项目已经配置
    {
        f_ini.open(QIODevice::ReadOnly | QIODevice::Text);
        QByteArray data = f_ini.readAll();
        f_ini.close(); //关闭文件
        QString s_ini(data);
        ui->ui_date_start->setDate(QDate::fromString(s_ini));

    }
    else
    {
        qDebug() << timechart_dir_saved + "/plan.ini" << " not exist";
        QString start_time = settings->value("start_time",QDate::currentDate().toString()).toString(); //获取设置的起始时间
        ui->ui_date_start->setDate(QDate::fromString(start_time));
    }
    // --------------------------------------------------------------
    //bottom
    QShortcut* shortcut = new QShortcut(Qt::CTRL + Qt::Key_S, this);
    QObject::connect(shortcut, &QShortcut::activated, ui->ui_btm_save, &QPushButton::click);
    // --------------------------------------------
    // 生成提示信息
    connect(table_day, &QTableWidget::cellDoubleClicked, this, &timechart_blck::on_table_day_double_click);
    connect(table_week, &QTableWidget::cellDoubleClicked, this, &timechart_blck::on_table_week_double_click);
    connect(table_quarter, &QTableWidget::cellDoubleClicked, this, &timechart_blck::on_table_quarter_double_click);
    connect(table_team, &QTableWidget::cellDoubleClicked, this, &timechart_blck::on_table_team_double_click);
    //右击标记完成

    // --------------------------------------------
    // 修改文件的提示信息
    act_table_ini_head();

    // --------------------------------------------
    // 定时检查开始
    time_10m = new QTimer(this);
    connect(time_10m, &QTimer::timeout, this, &timechart_blck::act_every10_minute);
    time_10m->start(600000); //600000ms, 10min, 尽量减少对正常程序的干扰
}

timechart_blck::~timechart_blck()
{
    delete ui;
}
void timechart_blck::act_table_ini_head()
{
    QStringList head_lab_state;

    for(int i =0; i < table_day->columnCount();i++)
    {
        //head_lab_state << QString::number(i);
        head_lab_state << ui->ui_date_start->date().addDays(i).toString()+ "~";
    }
    table_day->setHorizontalHeaderLabels(head_lab_state);
    head_lab_state.clear();
    for(int i =0; i < table_week->columnCount();i++)
    {
        //head_lab_state << QString::number(i);
        head_lab_state << ui->ui_date_start->date().addDays(i*7).toString() + "~";
    }
    table_week->setHorizontalHeaderLabels(head_lab_state);
    head_lab_state.clear();
    for(int i =0; i < table_quarter->columnCount();i++)
    {
        //head_lab_state << QString::number(i);
        head_lab_state << ui->ui_date_start->date().addDays(i*7*12).toString() + "~";
    }
    table_quarter->setHorizontalHeaderLabels(head_lab_state);
    head_lab_state.clear();
    for(int i =0; i < 1;i++)
    {
        head_lab_state << "季度目标";
    }
    table_team->setHorizontalHeaderLabels(head_lab_state);
}
void timechart_blck::on_ui_btm_load_dir_clicked()
{
    QString p_dir  = QFileDialog::getExistingDirectory
                            (this,
                             "Please choose an work dir",
                             "");
    if (p_dir.isEmpty())
    {
        qDebug() << "你取消了选择。";
        return;
    }
    ui->ui_lin_dir->setText(p_dir);
    settings->setValue("timechart_dir_saved",p_dir);

}
void timechart_blck::on_ui_date_start_dateChanged(const QDate &date)
{
    settings->setValue("start_time",date.toString()); //更新起点日期
    QFile f_ini(ui->ui_lin_dir->text() + "/plan.ini"); //判断是否存在对应的配置文件
    f_ini.open(QIODevice::WriteOnly | QIODevice::Text); //更新ini文件
    QByteArray data = ui->ui_date_start->date().toString().toUtf8();
    f_ini.write(data);
    f_ini.close();
    // --------------------------------------------
    // 如果不存在历史文件，则创建当前配置的计划
    act_file_create(ui->ui_lin_dir->text() + "/plan"+ui->ui_date_start->date().toString("yyyy_MM_dd")+"_day.csv",table_day);
    act_file_create(ui->ui_lin_dir->text() + "/plan"+ui->ui_date_start->date().toString("yyyy_MM_dd")+"_week.csv",table_week);
    act_file_create(ui->ui_lin_dir->text() + "/plan"+ui->ui_date_start->date().toString("yyyy_MM_dd")+"_quarter.csv",table_quarter);
    act_file_create(ui->ui_lin_dir->text() + "/plan"+ui->ui_date_start->date().toString("yyyy_MM_dd")+"_team.csv",table_team);
    //更新表格的头
    act_table_ini_head();
}


void timechart_blck::on_ui_btm_save_clicked()
{
    act_table_save(ui->ui_lin_dir->text() + "/plan"+ui->ui_date_start->date().toString("yyyy_MM_dd")+"_day.csv",table_day); //保存对应层次的时间计划
    act_table_save(ui->ui_lin_dir->text() + "/plan"+ui->ui_date_start->date().toString("yyyy_MM_dd")+"_week.csv",table_week); //保存对应层次的时间计划
    act_table_save(ui->ui_lin_dir->text() + "/plan"+ui->ui_date_start->date().toString("yyyy_MM_dd")+"_quarter.csv",table_quarter); //保存对应层次的时间计划
    act_table_save(ui->ui_lin_dir->text() + "/plan"+ui->ui_date_start->date().toString("yyyy_MM_dd")+"_team.csv",table_team); //保存对应层次的时间计划

    ui->ui_btm_save->setStyleSheet("background-color: green");
}

void timechart_blck::on_ui_btm_read_clicked()
{

    act_table_read(ui->ui_lin_dir->text() + "/plan"+ui->ui_date_start->date().toString("yyyy_MM_dd")+"_day.csv",table_day); //读取对应层次的时间计划
    act_table_read(ui->ui_lin_dir->text() + "/plan"+ui->ui_date_start->date().toString("yyyy_MM_dd")+"_week.csv",table_week); //读取对应层次的时间计划
    act_table_read(ui->ui_lin_dir->text() + "/plan"+ui->ui_date_start->date().toString("yyyy_MM_dd")+"_quarter.csv",table_quarter); //读取对应层次的时间计划
    act_table_read(ui->ui_lin_dir->text() + "/plan"+ui->ui_date_start->date().toString("yyyy_MM_dd")+"_team.csv",table_team); //读取对应层次的时间计划
}

void timechart_blck::act_table_save(QString fname, QTableWidget *table)
{
    QFile file(fname); //获取当前的文件

    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QMessageBox::critical(this, "错误", "无法保存文件: " + file.errorString());
        return;
    }

    QTextStream out(&file);
    // 获取表格数据
    int rows = table->rowCount();
    int cols = table->columnCount();
    for (int row = 0; row < rows; row++) {
        QStringList fields;

        for (int col = 0; col < cols; col++)
        {
            QTableWidgetItem *item = table->item(row, col);
            QString value = item ? item->text() : "";

            // 处理包含逗号的值，用引号包裹
            if (value.contains(',') && value.contains("\"") == false) // 判断字符串是否需要判断, 字符串不补充
            {
                value = "\"" + value.replace("\"", "\"\"") + "\"";
            }
            fields.append(value);
        }
        // 写入一行数据
        if(fields.size() == 1)
        {
            out << fields.at(0) << "\n"; //直接写入
        }
        else
        {
            out << fields.join(',') << "\n";
        }

    }

    file.close();
    table->resizeRowsToContents(); //更新写入视图
}

void timechart_blck::act_table_read(QString fname, QTableWidget *table)
{
    // detect if file is exist
    QFile file(fname);
    int index_cur = ui->ui_pages->currentIndex();
    ui->ui_pages->setCurrentIndex(3); //设置到最小的表格，防止数据被刷新
    if (file.open(QIODevice::ReadWrite | QIODevice::Text))
    {
        QTextStream in(&file);
        for(int row = 0; row < table->rowCount(); ++row) //按照表格格式读取文件
        {
            QString line = in.readLine(); //
            QStringList fields;

            fields = line.split(QRegularExpression(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"));
            // 设置单元格数据
            for (int col = 0; col < fields.size(); ++col)
            {
                QTableWidgetItem *item = new QTableWidgetItem(fields[col]);
                table->setItem(row, col, item); //大文件加载时不要停留在当前的页面
            }
            if(fields.size() < table->columnCount())
            {
                for(int col = fields.size(); col < table->columnCount(); col ++)
                {
                    QTableWidgetItem *item = new QTableWidgetItem(""); //初始化未配置的文件
                    table->setItem(row, col, item);
                }
            }
            ui->ui_prc_read->setValue(row * 100 / table->rowCount());
        }
        file.close();
        ui->ui_prc_read->setValue(100); // 设置结束
    } else
    {
        // 打开失败，处理错误
        qDebug() << "无法打开文件:" << file.errorString();
    }
    ui->ui_pages->setCurrentIndex(index_cur); //还原到原本的控件
    table->resizeRowsToContents();
}

void timechart_blck::act_file_create(QString fname,QTableWidget *table)
{
    QFile ftable(fname);
    if(ftable.exists()) //文件存在
    {
        qDebug() << "here has paln" << fname;
        act_table_read(fname,table);
    }
    else
    {
        ftable.open(QIODevice::WriteOnly | QIODevice::Text);
        ftable.close();
    }
}

void timechart_blck::on_table_day_double_click(int row, int column)
{
    //qDebug() << "site" << row << "x" << column;
    int cur_day  = column % 7; //第N天
    int cur_week = column / 7; //第N周
    int cur_quarter = cur_week / 12; //第N季度
    if(table_week->item(cur_day,cur_week) != nullptr)
    {
        ui->ui_txt_week->setText(table_week->item(cur_day,cur_week)->text());
    }
    if (table_quarter->item(cur_week,cur_quarter) == nullptr)
    {
        ui->ui_txt_quarter->setText(table_quarter->item(cur_week,cur_quarter)->text());
    }
    if(table_team->item(cur_quarter,0) == nullptr)
    {
        ui->ui_txt_team->setText(table_team->item(cur_quarter,0)->text());
    }

    //设置按钮颜色提示保存
    ui->ui_btm_save->setStyleSheet("background-color: yellow");

}
void timechart_blck::on_table_week_double_click(int row, int column)
{
    //qDebug() << "site" << row << "x" << column;
    int cur_day  = column; //第N天
    int cur_week = row; //第N周
    int cur_quarter = cur_week / 12; //第N季度
    if(table_week->item(cur_day,cur_week) != nullptr)
    {
        ui->ui_txt_week->setText(table_week->item(cur_day,cur_week)->text());
    }
    if (table_quarter->item(cur_week,cur_quarter) == nullptr)
    {
        ui->ui_txt_quarter->setText(table_quarter->item(cur_week,cur_quarter)->text());
    }
    if(table_team->item(cur_quarter,0) == nullptr)
    {
        ui->ui_txt_team->setText(table_team->item(cur_quarter,0)->text());
    }
    //设置按钮颜色提示保存
    ui->ui_btm_save->setStyleSheet("background-color: yellow");
}
void timechart_blck::on_table_quarter_double_click(int row, int column)
{
    //qDebug() << "site" << row << "x" << column;
    int cur_week = row; //第N周
    int cur_quarter = column; //第N季度
//    if(table_week->item(cur_day,cur_week) != nullptr)
//    {
//        ui->ui_txt_week->setText(table_week->item(cur_day,cur_week)->text());
//    }
    if(table_quarter->item(cur_week,cur_quarter) == nullptr)
    {
        ui->ui_txt_quarter->setText(table_quarter->item(cur_week,cur_quarter)->text());
    }
    if(table_team->item(cur_quarter,0) == nullptr)
    {
        ui->ui_txt_team->setText(table_team->item(cur_quarter,0)->text());
    }
    //设置按钮颜色提示保存
    ui->ui_btm_save->setStyleSheet("background-color: yellow");
}
void timechart_blck::on_table_team_double_click(int row, int column)
{
    //qDebug() << "site" << row << "x" << column;
    int cur_quarter = row; //第N季度
//    if(table_week->item(cur_day,cur_week) != nullptr)
//    {
//        ui->ui_txt_week->setText(table_week->item(cur_day,cur_week)->text());
//    }
//    if (table_quarter->item(cur_week,cur_quarter) == nullptr)
//    {
//        ui->ui_txt_quarter->setText(table_quarter->item(cur_week,cur_quarter)->text());
//    }
    if(table_team->item(cur_quarter,0) == nullptr)
    {
        ui->ui_txt_team->setText(table_team->item(cur_quarter,0)->text());
    }
    //设置按钮颜色提示保存
    ui->ui_btm_save->setStyleSheet("background-color: yellow");
}

void timechart_blck::act_every10_minute()
{

    // 获取当前时间
    QTime currentTime = QTime::currentTime();
    this->show();
    // 判断是否为整点
    if (currentTime.minute() < 10) //每10分钟监测一次是否允许弹出提示
    {
          QMessageBox::information(this, "提示", "一个小时过去了，当前时间是: " + currentTime.toString() ); //直接弹出当前时间
    }
}




void timechart_blck::on_ui_btm_finish_task_clicked()
{
    // 获取选中的单元格
    QList<QTableWidgetItem*> selectedItems = table_day->selectedItems();

    // 遍历选中的单元格
    for (QTableWidgetItem* item : selectedItems)
    {
        int row = item->row();
        int column = item->column();
        if(table_day->item(row, column) != nullptr) //判断单元格不为空
        {
           table_day->item(row,column)->setBackgroundColor(Qt::green); //任务完成标记绿色
           QString txt = table_day->item(row,column)->text() + "#finished";
           table_day->item(row,column)->setText(txt);
        }

    }
}


void timechart_blck::on_ui_btm_fail_task_clicked()
{
    // 获取选中的单元格
    QList<QTableWidgetItem*> selectedItems = table_day->selectedItems();

    // 遍历选中的单元格
    for (QTableWidgetItem* item : selectedItems)
    {
        int row = item->row();
        int column = item->column();
        if(table_day->item(row, column) != nullptr)
        {
            table_day->item(row,column)->setBackgroundColor(Qt::red); //任务失败标记红色
            QString txt = table_day->item(row,column)->text() + "#failed";
            table_day->item(row,column)->setText(txt);
        }
    }
}


void timechart_blck::on_ui_btm_cancel_task_clicked()
{
    // 获取选中的单元格
    QList<QTableWidgetItem*> selectedItems = table_day->selectedItems();

    // 遍历选中的单元格
    for (QTableWidgetItem* item : selectedItems)
    {
        int row = item->row();
        int column = item->column();
        if(table_day->item(row, column) != nullptr)
        {
            table_day->item(row,column)->setBackground(QBrush()); //任务取消消除颜色
        }

    }
}

